package com.spring.shops.admin.controller.order;

import com.spring.shops.dao.TzOrderMapper;
import com.spring.shops.dao.TzUserAddrOrderMapper;
import com.spring.shops.model.dto.OrderPageDTO;
import com.spring.shops.model.entity.TzOrder;
import com.spring.shops.model.entity.TzUserAddr;
import com.spring.shops.model.result.OrderResult;
import com.spring.shops.model.vo.ExportExcelVo;
import com.spring.shops.model.vo.Order1Vo;
import com.spring.shops.model.vo.OrderRecordsVo;
import com.spring.shops.model.vo.OrderVo;
import com.spring.shops.service.OrderService;
import com.spring.shops.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/order/order")
@CrossOrigin(origins = "*")
public class OrderController {

    @Resource
    private TzUserAddrOrderMapper tzUserAddrOrderMapper;

    @Resource
    private OrderService orderService;
    @Resource
    private TzOrderMapper tzOrderMapper;

    @GetMapping("/page")
    public OrderResult OrderSearchPage(@RequestParam("current") String current,
                                       @RequestParam("size") String size,
                                       @RequestParam(value = "orderNumber", defaultValue = "") String orderNumber,
                                       @RequestParam(value = "status", defaultValue = "-1") int status,
                                       @RequestParam(value = "startTime", defaultValue = "") String startTime,
                                       @RequestParam(value = "endTime", defaultValue = "") String endTime) {
        OrderVo orderVo = new OrderVo();
        orderVo.setCurrent(Integer.parseInt(current));
        orderVo.setPages(Integer.parseInt(size));
        orderVo.setPages(Integer.parseInt(current));
        OrderPageDTO orderPageDTO = new OrderPageDTO();
        orderPageDTO.setStatus(status);
        orderPageDTO.setStartTime(startTime);
        orderPageDTO.setOrderNumber(orderNumber);
        orderPageDTO.setEndTime(endTime);
        System.out.println(startTime);
        System.out.println(endTime);
        OrderVo orderVo1 = orderService.orderPageSearch(orderVo, orderPageDTO);
        return OrderResult.orderPageSearchSuccess(orderVo1);
    }

    @GetMapping("/orderInfo/{id}")
    public OrderResult info(@PathVariable("id") String id) {
        OrderRecordsVo info = orderService.info(id);
        return OrderResult.orderInfoSuccess(info);
    }

    @GetMapping("waitingConsignmentExcel")
    public void exportWait(@RequestParam("consignmentName") String consignmentName,
                           @RequestParam("consignmentMobile") String consignmentMobile,
                           @RequestParam("consignmentAddr") String consignmentAddr, HttpServletResponse resp) throws Exception {

        List<ExportExcelVo> exportExcelVos = orderService.waitExcel(consignmentName, consignmentMobile, consignmentAddr);

        String[] title = {"收件人", "手机", "收货地址", "商品名称", "数量", "发件人姓名", "发件人手机号", "发货地址", "备注", "订单编号"};
        String fileName = "未发货名单.xls";

        String content[][] = new String[exportExcelVos.size()][];
        String sheetName = "订单信息表";
        for (int i = 0; i < exportExcelVos.size(); i++) {
            content[i] = new String[title.length];
            ExportExcelVo obj = exportExcelVos.get(i);
            content[i][0] = obj.getUserName().toString();
            content[i][1] = obj.getUserMobile().toString();
            content[i][2] = obj.getUserAddr().toString();
            content[i][3] = obj.getShopsName().toString();
            content[i][4] = obj.getShopsCount().toString();
            content[i][5] = obj.getShopOwnerName().toString();
            content[i][6] = obj.getShopOwnerMobile().toString();
            content[i][7] = obj.getShopAddr().toString();
            content[i][8] = obj.getMsg().toString();
            content[i][9] = obj.getOrderId().toString();
        }
        HSSFWorkbook wb = ExcelUtil.hssfWorkbook(sheetName, title, content, null);

        try {
            this.setResponseHeader(resp, fileName);
            OutputStream os = resp.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @GetMapping("/soldExcel")
    @ResponseBody
    public void page( HttpServletResponse response) {

        List<TzOrder> tzOrders = tzOrderMapper.selectByIsPayed();
        List<Order1Vo> list=new ArrayList<>();
        for (TzOrder tzOrder : tzOrders) {
            Order1Vo order1Vo = new Order1Vo();
            order1Vo.setOrderNumber(tzOrder.getOrderNumber());
            order1Vo.setCreateTime(tzOrder.getCreateTime());
            order1Vo.setProdName(tzOrder.getProdName());
            order1Vo.setTotal(tzOrder.getTotal());
            order1Vo.setActualTotal(tzOrder.getActualTotal());
            order1Vo.setFreight_amount(tzOrder.getFreightAmount());
            order1Vo.setProductNums(tzOrder.getProductNums());
            TzUserAddr tzUserAddrs = tzUserAddrOrderMapper.selectbyUserId(tzOrder.getUserId());
            String s=tzUserAddrs.getProvince()+tzUserAddrs.getCity()+tzUserAddrs.getArea()+tzUserAddrs.getAddr();
            order1Vo.setAddr(s);
            order1Vo.setReceiver(tzUserAddrs.getReceiver());
            order1Vo.setMobile(tzUserAddrs.getMobile());
            list.add(order1Vo);
        }


        String[] title = {"订单编号","下单时间","收件人","手机","收货地址","商品名称"
                ,"数量","订单应付","订单运费","订单实付"};

        String fileName = "销售信息整理"+System.currentTimeMillis()+".xls";

        String sheetName = "销售信息";
        String[][] content = new String[list.size()][title.length];


        for (int i = 0; i < list.size(); i++) {
            Order1Vo order1Vo = list.get(i);
            content[i][0] =order1Vo.getOrderNumber();
            content[i][1] =order1Vo.getCreateTime().toString();
            content[i][2] = order1Vo.getReceiver().toString();
            content[i][3] = order1Vo.getMobile().toString();
            content[i][4] = order1Vo.getAddr().toString();
            content[i][5] =order1Vo.getProdName();
            content[i][6] =order1Vo.getTotal().toString();
            content[i][7] = order1Vo.getTotal().toString();
            content[i][8] = order1Vo.getFreight_amount().toString();
            content[i][9] = order1Vo.getActualTotal().toString();
        }
        HSSFWorkbook wb = ExcelUtil.hssfWorkbook(sheetName, title, content, null);


        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
